package crawler.web.engine.custom;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;

import library.Tracer;
import library.bean.Point2D;
import library.functions.Function0PV;
import library.thread.MyThread;
import library.utils.date.DateUtils;
import library.utils.probability.ProbabilityUtils;

import org.springframework.stereotype.Component;

import crawler.web.engine.config.ConfigBatchInit;

/**
 * 模拟人浏览行为(晚上停止...) 在行为过滤中<br>
 * p1的概率确认是不是在规定的时间区内抓取,不是则暂停m分钟<br>
 * p2的概率暂停n分钟<br>
 * 
 * @author waynechen Jun 4, 2012 5:38:53 PM
 */
@Component(value = "HumanActionSimulator4VisitingWeb")
public class HumanActionSimulator4VisitingWeb implements Function0PV {
	private List<Point2D<String>> intervals = new ArrayList<Point2D<String>>();
	private double p1;
	private double p2;
	private P2StopTime p2StopTime;

	private class P2StopTime {
		private int min;
		private int max;

		public P2StopTime(String min, String max) {
			this.min = Integer.parseInt(min);
			this.max = Integer.parseInt(max);
		}

		public int getTime() {
			int nextInt = ProbabilityUtils.RAN.nextInt(max - min);
			nextInt += min;
			return nextInt * 1000 * 60;
		}
	}

	public HumanActionSimulator4VisitingWeb() {
		List<String> list = ConfigBatchInit.getStringList("HumanAction4VisitingWeb");
		for (String line : list) {
			line = line.replace(" ", "");
			if (line.startsWith("p1=")) {
				p1 = Double.parseDouble(line.split("=")[1]);
			} else if (line.startsWith("p2=")) {
				p2 = Double.parseDouble(line.split("=")[1]);
			} else if (line.startsWith("p2StopTime=")) {
				String[] split = line.split("=")[1].split("~");
				p2StopTime = new P2StopTime(split[0], split[1]);
			} else {
				String[] split = line.split("~");
				intervals.add(new Point2D<String>(split[0], split[1]));
			}
		}
	}

	private boolean inInterval() throws ParseException {
		long curr = System.currentTimeMillis();
		for (Point2D<String> i : intervals) {
			long min = DateUtils.composeTimeOfToday(i.getX()).getTime();
			long max = DateUtils.composeTimeOfToday(i.getY()).getTime();
			if (min <= curr && curr <= max)
				return true;
		}
		return false;
	}

	@Override
	public void apply() {
		if (ProbabilityUtils.probability(p2))
			MyThread.sleepWithoutThrowing(p2StopTime.getTime());
		if (ProbabilityUtils.probability(p1)) {
			try {
				while (!inInterval()) {
					MyThread.sleepWithoutThrowing(1000 * 60);
				}
			} catch (Exception e) {
				Tracer.exception(e);
			}
		}
	}

}
